﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using SManage.LibExtension;
using Lextm.SharpSnmpLib;
using Lextm.SharpSnmpLib.Messaging;

namespace SManage.TraceEngine
{
    internal static class DiscovererUtil
    {
        public static IList<IPAddress> GetInterfaceIps(IPAddress ip) {
            String oid = ".1.3.6.1.2.1.4.20.1";
            var table = oid.ToOid().WalkFromIPAddress(ip).ToTable(5);
            var list = from i in table
                       select i[0].Data
                           .ToString().Trim()
                           .ToIPAddress();
            return list.ToList();
        }

        public static IList<IPAddress> GetNeighborIps(IPAddress ip) {
            String oid1 = ".1.3.6.1.2.1.4.21.1";
            var table1 = oid1.ToOid().WalkFromIPAddress(ip).ToTable(13);
            var list1 = new List<IPAddress>();
            if (table1 != null) {
                list1 = (from i in table1
                         where i[7].Data.ToInt32() == 4
                         select i[6].Data
                             .ToString().Trim()
                             .ToIPAddress()).ToList();               
            }

            String oid2 = ".1.3.6.1.2.1.4.22.1";
            var table2 = oid2.ToOid().WalkFromIPAddress(ip).ToTable(4);
            var list2 = new List<IPAddress>();
            if (table2 != null) {
                list2 = (from i in table2
                         where i[3].Data.ToInt32() == 3
                         select i[2].Data
                             .ToString().Trim()
                             .ToIPAddress()).ToList();
            }
            
            return list1.Concat(list2).Distinct().ToList();
        }

        public static Boolean Discovery(IPAddress ip,VersionCode version) { 
            var port = SyncEngineConfig.Default.Port;
            var community = SyncEngineConfig.Default.Community;
            var item = new SyncItem(ip, version, port, community);

            IList<Variable> result = new List<Variable>();
            IList<Variable> variables = new List<Variable> { new Variable(new ObjectIdentifier(".1.3.6.1.2.1.1.1.0")) };
            for (int i = 0; i < 3; i++) {
                try {
                    result = Messenger.Get(item.Version,
                        item.EndPoint,
                        item.Community,
                        variables,
                        4000);
                } catch {
                    result = null;
                }
                if (result != null) {
                    break;
                }
            }
            //var result = ".1.3.6.1.2.1.1.1.0".ToOid().GetFromSyncItem(item);

            return result == null ? false : true;
        }
    }
}
